using AutoMapper;
using B.S.Sterilizationcenter.Domain.yjb;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Writer.API.Appliaction.Commends.Yjb.PendingPrescription;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Writer.API.Appliaction.CommandHandlers.Yjb.PendingPrescription
{
    public class UpdatePendingPrescriptionCommandHandler : IRequestHandler<UpdatePendingPrescriptionCommand, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public UpdatePendingPrescriptionCommandHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdatePendingPrescriptionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> result = new ApiResult<int>();
                
                var existingRecord = await db.Queryable<Domain.yjb.PendingPrescription>()
                    .FirstAsync(p => p.PendingPrescriptionId == request.PendingPrescriptionId);
                
                if (existingRecord != null)
                {
                    mapper.Map(request, existingRecord);
                    var res = await db.Updateable(existingRecord).ExecuteCommandAsync();
                    
                    if (res > 0)
                    {
                        result.Code = ApiEnums.修改成功;
                        result.Msg = "修改成功";
                    }
                    else
                    {
                        result.Code = ApiEnums.修改失败;
                        result.Msg = "修改失败";
                    }
                }
                else
                {
                    result.Code = ApiEnums.修改失败;
                    result.Msg = "记录不存在";
                }
                
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
} 